const { series, src, dest, watch } = require('gulp');
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const minifyCss = require('gulp-minify-css')
const rename = require('gulp-rename')
const babel = require ('gulp-babel')
const uglify = require('gulp-uglify')
const htmlmin = require('gulp-htmlmin')
const ts = require('gulp-typescript')
const server=require("browser-sync").create();
// const {concat,babel,uglify,sass,rename,minifyCss}=require("gulp")();

function copyTask(done) {
    return src(
      'assets/**/*'
     
    )
    .pipe(dest('dist/assets'))
    done();
  }

  function htmlTask() {
    return src('public/**/*.html')
      .pipe(htmlmin({ collapseWhitespace: true }))
      .pipe(dest('dist'))
     
      .on("end",server.reload);

  }
  

  function reloadCss(done){
    src(["./style/scss/*.scss",
    "./style/css/*.css" ])
    .pipe(sass())
    .pipe(concat("./style/css/*.css"))
    .pipe(minifyCss())
    .pipe(rename("main.min.css"))
    .pipe(dest("./dist/css/"))
    .on("end",server.reload);
    done();
   
 
}

function reloadJs(done){
  src("./src/*.js")
  .pipe(babel({
      presets: ['@babel/env']
  }))
  .pipe(concat("main.js"))
  .pipe(uglify())
  .pipe(rename("main.min.js"))
  .pipe(dest("./dist/js/"))
  .on("end",server.reload);
  done();
}

function reloadTs(done){
  src("./ts/*.ts")
  .pipe(babel({
      presets: ['@babel/env']
  }))
  .pipe(concat("main.ts"))
  .pipe(uglify())
  .pipe(rename("main.min.ts"))
  .pipe(dest("./dist/ts/"))
  .on("end",server.reload);
  done();
}

function initServer(done){  //初始化服务，需要加done
  server.init({
      host:"localhost",
      port:7777,
      server:"./dist"
  });
  done();
}

function watchContent(done){
  watch("./src/*.js",reloadJs);
  watch("./ts/*.ts",reloadTs);
  watch("./style/**/*",reloadCss);
  watch("./public/**/*.html",htmlTask);
  done();
}




exports.default=series([copyTask,htmlTask,reloadJs,reloadTs,reloadCss,initServer],watchContent) 
